/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package deatax.network;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 *
 * @author pson
 */
public class ClientHandler {

    Socket c_socket;
    PrintWriter output;
    BufferedReader input;
    boolean alive;

    public ClientHandler(Socket s) {
        try {
            c_socket = s;
            input = new BufferedReader(new InputStreamReader(c_socket.getInputStream()));
            output = new PrintWriter(c_socket.getOutputStream(), true);
            alive = false;
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    
    public synchronized void close() {
        alive = false;
    }

    public synchronized void sendMessage(int message_type, String[] params) {
        StringBuilder sb = new StringBuilder();
        if (params != null) {
            for (String p : params) {
                sb.append(p).append(":");
            }
        }
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1);
        }
        sendMessage(message_type + "|" + sb);
    }
    
    public synchronized void sendMessage(String line) {
        output.println(line);
    }

    public synchronized void start() {
        alive = true;
        new ClientHandlerThread().start();
    }

    private class ClientHandlerThread extends Thread {

        @Override
        public void run() {
            String line;
            try {
                while ((line = input.readLine()) != null && alive) {
                    System.out.println("handler got a message" + line);
                    Server.get().sendMessages(line);
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            try {
                input.close();
                output.close();
                c_socket.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}
